package cn.chengpengper.rpc.loadbalancer.random.weight.enhanced;

import cn.chengpengper.rpc.loadbalancer.base.BaseEnhancedServiceLoadBalancer;
import cn.chengpengper.rpc.protocol.meta.ServiceMeta;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Random;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class RandomWeightServiceEnhancedLoadBalancer extends BaseEnhancedServiceLoadBalancer {
    @Override
    public ServiceMeta select(List<ServiceMeta> servers, int hashCode, String sourceIp) {
        log.info("基于增强型加权随机算法的负载均衡策略");
        servers = this.getWeightServiceMetaList(servers);
        if (servers == null || servers.isEmpty()) {
            return null;
        }
        Random random = new Random();
        int index = random.nextInt(servers.size());
        return servers.get(index);

    }
}
